﻿var app = angular.module('app_store', ['ngRoute', 'StoreService',]).config(function ($httpProvider) {
    $httpProvider.defaults.transformRequest = function (obj) {
        var str = [];
        for (var p in obj) {
            str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
        }
        return str.join("&");
    };
    $httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded; charset=utf-8';
});
//服务
var StoreService = angular.module('StoreService', []);
//请求服务
StoreService.factory('requestService', function ($http, $q) {
    var request = {
        method: 'POST',
        url: '',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8' },
        data: {}
    };
    var postData = {
        lists: function (type, page) {
            request.method = "get";
            request.url = "../api/product/lists?key=" + type + "&page=" + page;
            return requestService($http, $q, request);
        },
        product_add: function (data) {
            request.method = "post";
            request.url = "../api/product/lists";
            request.data = data;
            return requestService($http, $q, request);
        },
        product_delete: function (id) {
            request.method = "DELETE";
            request.url = "../api/product/lists?id=" + id;
            return requestService($http, $q, request);
        },
        product_put: function (data) {
            request.method = "put";
            request.url = "../api/product/lists";
            request.data = data;
            return requestService($http, $q, request);
        }
    };
    return postData;
});
function requestService($http, $q, request) {
    var deferred = $q.defer(); // 声明延后执行，表示要去监控后面的执行  
    $http(request).
    success(function (data, status, headers, config) {
        deferred.resolve(data);  // 声明执行成功，即http请求数据成功，可以返回数据了  
    }).
    error(function (data, status, headers, config) {

        deferred.reject(data);   // 声明执行失败，即服务器返回错误  
    });
    return deferred.promise;   // 返回承诺，这里并不是最终数据，而是访问最终数据的API  
};